package com.zyz.demo.controller;


import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.ICaptcha;
import cn.hutool.captcha.LineCaptcha;
import com.zyz.demo.model.CaptchaInfo;
import com.zyz.demo.model.Result;
import com.zyz.demo.model.UserInfo;
import com.zyz.demo.service.UserService;
import com.zyz.demo.utils.JwtUtils;
import com.zyz.demo.utils.SecretUtils;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.sql.SQLIntegrityConstraintViolationException;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private CaptchaInfo captchaInfo;
//    private final Long CAPTCHA_TIME = 6000L;
    @Autowired
    private UserService userService;
    @RequestMapping("/login")
    public Result login(String userName, String password, String userCaptcha,HttpSession session) {
        log.info("userController.login userName:"+userName);
        log.info("userController.login userCaptcha:"+userCaptcha);
        if (!StringUtils.hasLength(userName) || !StringUtils.hasLength(password)) {
            return Result.fail("账号或者密码不能为空");
        }
        if (!StringUtils.hasLength(userCaptcha)) return Result.fail("请输入验证码");
        // 判断验证码是否正确或失效
        if (!userCaptcha.equalsIgnoreCase((String) session.getAttribute(captchaInfo.getCaptchaCodeKye()))) {
            return Result.fail("验证码错误");
        }
        if ((long)session.getAttribute(captchaInfo.getCaptchaTimeKey()) - System.currentTimeMillis() < 0) {
            return Result.fail("验证码已失效,请重新获取");
        }
        // 验证账号密码是否正确
        UserInfo userInfo = null;
        try{
            userInfo = userService.login(userName);
        } catch(Exception e) {
            log.error("userController.login,数据库查询异常,e : " + e.getMessage());
        }
        if (userInfo == null) {
            log.warn("无此人信息");
            return Result.fail("无此人信息");
        }
        if (!SecretUtils.verify(password,userInfo.getPassword())) {
            log.warn("密码验证失败");
            return Result.fail("密码错误");
        }
//        if (!password.equals(userInfo.getPassword())) {
//            return Result.fail("密码错误");
//        }
        // 账号密码正确
        Map<String,Object> claims = new HashMap<>();
        claims.put("id",userInfo.getId());
        claims.put("userName",userInfo.getUserName());
        return Result.success(JwtUtils.getJwt(claims));

    }
    @RequestMapping("/getCaptcha")
    public void captcha(HttpServletResponse response, HttpSession session){
        //定义图形验证码的长和宽
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(captchaInfo.getWide(), captchaInfo.getHeight());

        ICaptcha captcha = lineCaptcha;
        try {
            response.setHeader("Pragma","no-cache");
            response.setContentType("image/jpeg");
            captcha.write(response.getOutputStream());
            log.info("验证码："+captcha.getCode());
            // 设置验证码和有效期
            session.setAttribute(captchaInfo.getCaptchaCodeKye(),captcha.getCode());
            session.setAttribute(captchaInfo.getCaptchaTimeKey(), System.currentTimeMillis()+ captchaInfo.getCaptchaTime());
            response.getOutputStream().close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @RequestMapping("/getUserInfo")
    public UserInfo getUserInfo(HttpServletRequest request) {
        String token = request.getHeader("user_token");
        Integer userId = JwtUtils.getUserIdByToken(token);
        log.info("getUserInfo.userId: {}",userId);
        UserInfo userInfo = userService.getUserInfo(userId);
        // 查询作者发布过多少文章
        int blogSize = userService.getUserBlogSize(userId);
        userInfo.setBlogSize(blogSize);
        log.info("userInfo:"+userInfo);
        return userInfo;
    }

    @RequestMapping("/getAuthorInfo")
    public UserInfo getAuthorInfo(Integer blogId) {
        log.info("user.getAuthorInfo blogId:"+blogId);
        Assert.notNull(blogId,"blogId为空");
        UserInfo userInfo = userService.getAuthorInfo(blogId);
        // 查询作者发布过多少文章
        int blogSize = userService.getUserBlogSize(userInfo.getId());
        userInfo.setBlogSize(blogSize);
        return userInfo;
    }

    @RequestMapping("/register")
    public Result register(UserInfo userInfo) {
        // 判断参数是否为空
        if (!StringUtils.hasLength(userInfo.getUserName())) {
            log.warn("register 用户名为空");
            return Result.fail("请填写用户名");
        }
        if (!StringUtils.hasLength(userInfo.getPassword())) {
            log.warn("register 密码为空");
            return Result.fail("请填写密码");
        }
        if (!StringUtils.hasLength(userInfo.getGithubUrl())) {
            log.warn("register github为空");
            return Result.fail("请填写github");
        }
        if (!StringUtils.hasLength(userInfo.getEmail())) {
            log.warn("register 邮箱为空");
            return Result.fail("请填写邮箱");
        }
        // 密码加密
        String secretPassword = userService.secret(userInfo.getPassword());
        userInfo.setPassword(secretPassword);
        // 判断索引是否已存在，已存在则不进行注册
        if (userService.checkIndexExist(userInfo.getUserName())) {
            log.warn("索引重复！");
            return Result.fail("用户名重复");
        }

        // 调用userService接口
        try {
            int result = userService.register(userInfo);
            if (result == 1) {
                return Result.success("");// 成功
            }
        } catch (Exception e){
            // 注册（添加）失败
            log.error(e.getMessage());
        }
        return Result.fail("后端内部错误");
    }
}
